package com.atguigu.weixin.controller;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.atguigu.crud.bean.Wxqr;
import com.atguigu.crud.bean.Wxuser;
import com.atguigu.crud.service.WxkfService;
import com.atguigu.crud.service.WxqrService;
import com.atguigu.crud.service.WxuserService;
import com.atguigu.weixin.model.WeixinFianlValue;

@Controller
@RequestMapping("/weixinUser")
public class WeixinUserController {
	@Autowired
	private WxuserService wxuserService;
	
	@Autowired
	private WxqrService wxqrService;
	
	
	@Autowired
	private WxkfService  wxkfService;
	//绑定新用户
	//绑定已存在的用户
	
	
	@RequestMapping("/list")
	public String list(Model model) {
		model.addAttribute("users", wxuserService.list());
		return "admin/wxuser/u_list";	
	}
	
	
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String login() {
		
		System.out.println("@@@@@@@@@@@@@@此处是登录跳转页面");
		return "admin/wxuser/login";
	}
	
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String add(String username,String password,HttpSession session) {
		Wxuser u = wxuserService.login(username, password);
		session.setAttribute("user", u);
		return "redirect:/weixinUser/list";
	}
	
	/**
	 *1、 绑定新用户 
	 * @return
	 * @throws IOException 
	 */
@RequestMapping(value="/bindNewUser",method=RequestMethod.GET)
public String bindNewUser(Model model,HttpSession session,HttpServletResponse resp) throws IOException{
	
	Wxuser u=(Wxuser)session.getAttribute("user");
	
	if(u==null){resp.sendRedirect("/weixinUser/login");}
	if(u.getBind()==1)return "redirect:/weixinUser/list";//如果已经绑定
	model.addAttribute("user", u);
	return "admin/wxuser/bindNewUser";
}

/**
 *2、 绑定新用户  
 * @return
 * @throws IOException 
 */
@RequestMapping(value="/bindNewUser",method=RequestMethod.POST)
public String bindNewUser(String username,String password,HttpSession session,HttpServletResponse resp) throws IOException {
	Wxuser u=(Wxuser)session.getAttribute("user");
	if(u==null){resp.sendRedirect("/weixinUser/login");}
	
	System.out.println("%%%%%%%%%%%%%%%%%%%%%绑定新用户的id");
	System.out.println("为："+u.getId());
	System.out.println("username:"+u.getUsername());
	
	Wxuser tu=wxuserService.loadByWxuserId(u.getId());
	tu.setBind(1);
	tu.setUsername(username);
	tu.setPassword(password);
	wxuserService.update(tu);
	session.setAttribute("user",tu);
	return "redirect:/weixinUser/list";
}

/**
 * 绑定存在的用户
 * @return
 * @throws IOException 
 */
@RequestMapping(value="/bindExistUser",method=RequestMethod.GET)
public String bindExistUser(Model model,HttpSession session,HttpServletResponse resp) throws IOException{
	Wxuser u=(Wxuser)session.getAttribute("user");
	if(u==null){resp.sendRedirect("/weixinUser/login");}
	
	
   return "admin/wxuser/bindExistUser";
}


/**
 * 绑定存在的用户 保存
 * @return
 * @throws IOException 
 */
@RequestMapping(value="/bindExistUser",method=RequestMethod.POST)
public String bindExistUser(Model model,String username,String password,HttpSession session,HttpServletResponse resp) throws IOException{
	Wxuser u=(Wxuser)session.getAttribute("user");
	if(u==null){resp.sendRedirect("/weixinUser/login");}
	Wxuser tu=wxuserService.loadByWxusername(username);
	
	if(tu.getPassword().equals(password)){
		 tu.setBind(1);
		 tu.setImgurl(u.getImgurl());
		 tu.setSex(u.getSex());
		 tu.setStatus(1);
		 tu.setNickname(u.getNickname());
		 tu.setOpenid(u.getOpenid());
		 wxuserService.update(tu);
		 //wxuserService.delete(u.getId());
		 session.setAttribute("user", tu);
	}else{
		throw new RuntimeException("原始的密码输入出错");
	}
	
   return "redirect:/weixinUser/list";
}

//忘记密码
    @RequestMapping(value="/forgetPwd",method=RequestMethod.GET)
	public String  forgetPassword(HttpSession session,Model model){
    	
    	Wxuser u = (Wxuser)session.getAttribute("user");
		if(u.getBind()==0) {
			throw new RuntimeException("请绑定用户之后才能在微信中修改密码！");
		}
		model.addAttribute("user", u);
    	
    	return "admin/wxuser/forgetPwd";
	}
    
	@RequestMapping(value="/forgetPwd",method=RequestMethod.POST)
	public String forgetPassword(HttpSession session,String password) {
		Wxuser u = (Wxuser)session.getAttribute("user");
		if(u.getBind()==0) {
			throw new RuntimeException("请绑定用户之后才能在微信中修改密码！");
		}
		u.setPassword(password);
		wxuserService.update(u);
		return "redirect:/weixinUser/list";
		
	}
	
	//扫码登录  
	//实现方式，先访问页面，内部会调用微信生成二维码 带场景参数的snum 的二维码。
	//然后再扫描二维码 会传场景值，snum 
	 @RequestMapping(value="/qrlogin")
	 private String qrlogin(Model model){
	  Wxqr wq=generateLoginQr();
	  try {
		wxqrService.add(wq);
		model.addAttribute("wq", wq);
	} catch (IllegalAccessException | InvocationTargetException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
		 return "admin/wxuser/qrlogin";
	 }
    
	 private Wxqr generateLoginQr(){
		 Wxqr wq=new Wxqr();
		 wq.setName("扫码登录");
		 wq.setMsg("扫码登录");
		 wq.setSnum(RandomUtils.nextInt()+(Wxqr.MAX_BASE_SNUM+1));//临时场景
		 wq.setStatus(0);
		 wq.setType(WeixinFianlValue.TEMP_LOGIN);//临时登录
		 return wq;
	 }
	 
	 /**
	  * 使用轮循的方式提交登录，然后把用户信息存到session中去，最后来实现登录
	  * @return
	 * @throws IOException 
	  */
	 @RequestMapping(value="checkqrlogin")
	 public void checkqrlogin(int snum,HttpSession session,HttpServletResponse resp) throws IOException{
		 Wxqr wq=wxqrService.loadBySnum(snum);
		 resp.setContentType("text/txt");
		 if(wq.getQrdata()!=null&&wq.getStatus()==1){
			 String openid=wq.getQrdata();
			 Wxuser u= wxuserService.loadByOpenid(openid);
			 session.setAttribute("user", u);
			 resp.getWriter().println(1);
		 }else{
			 resp.getWriter().println(0);
		 }
		
		 
	 }
	 
	 
	 @RequestMapping(value="addKf",method=RequestMethod.GET)
	 public String addKf(){
		 
		 return "admin/wxuser/kf";
	 }
	 
	 @RequestMapping(value="addKf",method=RequestMethod.POST)
	 public String addKf(String account,String nickname,String password ){
		 wxkfService.add(account, nickname, password);
		 return "admin/wxuser/kf";
	 }
	
}
